package com.cj.media.mediacodec

import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.lang.Exception

class LocalSurfaceView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : SurfaceView(context, attrs, defStyleAttr), Camera.PreviewCallback, SurfaceHolder.Callback {

    private var mCamera:Camera? = null
    private var size:Camera.Size? = null
    private var buffer:ByteArray? = null
    private var cameraEncoder:CameraEncoder? = null

    private val screen_width: Int = 1280
    private val screen_height: Int = 720

    init {
        holder.addCallback(this)
    }

    fun startPreview(){
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)
        mCamera?.let {
            val parameters = it.parameters
            size = parameters.pictureSize

            try {
                it.setPreviewDisplay(holder)
                it.setDisplayOrientation(90)
                //buffer = ByteArray(size!!.width * size!!.height * 3 / 2)
                buffer = ByteArray(screen_width * screen_height * 3 / 2)
                it.addCallbackBuffer(buffer)
                it.setPreviewCallbackWithBuffer(this)
                it.startPreview()
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        if(cameraEncoder == null){
            //cameraEncoder = CameraEncoder(size!!.width,size!!.height,context.getExternalFilesDir(null)!!.absolutePath + "/codec.h264",context.getExternalFilesDir(null)!!.absolutePath + "/codecH264.txt" )
            cameraEncoder = CameraEncoder(screen_width,screen_height,context.getExternalFilesDir(null)!!.absolutePath + "/codec.h264",context.getExternalFilesDir(null)!!.absolutePath + "/codecH264.txt" )
        }
        data?.let {
            cameraEncoder!!.encodeFrame(it)
            mCamera?.addCallbackBuffer(buffer)
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }

}